package com.ts.mediacodec

import android.media.MediaCodec
import android.media.MediaCodecInfo
import android.media.MediaFormat
import android.media.MediaFormat.MIMETYPE_VIDEO_AVC
import com.ts.utils.FileUtils

class H264Decode {
    var mediaCodec: MediaCodec? = null
    var width: Int = 0
    var height: Int = 0

    constructor(width: Int, height: Int) {
        this.width = width
        this.height = height
    }

    fun  startLive(){
        try {
            mediaCodec = MediaCodec.createEncoderByType(MIMETYPE_VIDEO_AVC)
            var mediaFormat = MediaFormat.createVideoFormat(MIMETYPE_VIDEO_AVC, width, height);
            mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, width * height)
            mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15)
            mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2) //IDR帧刷新时间
            mediaFormat.setInteger(
                MediaFormat.KEY_COLOR_FORMAT,
                MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible
            )
            mediaCodec?.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
            mediaCodec!!.start()
        }catch (e:Exception){
            e.printStackTrace()
        }

    }

    public fun encodeFrame(byteArray: ByteArray){
        //去问dsp要缓存空间的index
        var inputBufferIndex=mediaCodec?.dequeueInputBuffer(10000)
        val bufferInfo = MediaCodec.BufferInfo()
        if (inputBufferIndex != null) {
            if (inputBufferIndex>=0){

                var inputBuffer=mediaCodec?.getInputBuffer(inputBufferIndex);
                inputBuffer?.clear()
                inputBuffer?.put(byteArray)
                mediaCodec?.queueInputBuffer(inputBufferIndex, 0, byteArray.size,computPts(),0)
                index++
            }
        }

        var outputBufferIndex=mediaCodec?.dequeueOutputBuffer(bufferInfo,10000)
        if (outputBufferIndex!! >=0){
          var outputBuffer=mediaCodec?.getOutputBuffer(outputBufferIndex)
          var data=ByteArray(bufferInfo.size)
           outputBuffer?.get(data)
            FileUtils.writeBytes(data)
            FileUtils.writeContent(data)
            mediaCodec!!.releaseOutputBuffer(outputBufferIndex, false)
        }
    }
    var index: Int = 0
    fun computPts(): Long {
        return 1000000 / 15L * index
    }
}